<template>
  <div class="signature-view">
    <el-card class="signature-card">
      <div v-if="loading" class="loading-container">
        <i class="el-icon-loading"></i>
        <p>加载中...</p>
      </div>
      <div v-else-if="error" class="error-container">
        <i class="el-icon-warning-outline"></i>
        <p>{{ error }}</p>
        <el-button type="primary" size="small" @click="goBack">返回</el-button>
      </div>
      <template v-else>
        <signature-pad
          :approval-id="approvalId"
          :node-id="nodeId"
          :approval-node-name="approvalNodeName"
          :approval-user-name="approvalUserName"
          :approval-roles="approvalRoles"
          :show-amount="showAmount"
          :approval-amount="approvalAmount"
          :show-goods-info="showGoodsInfo"
          :goods-list="goodsList"
          @signed="handleSignatureComplete"
          @cancel="goBack"
        />
        <div v-if="showGoodsInfo" class="goods-info">
          <h3>货物信息</h3>
          <el-table v-if="goodsList.length > 0" :data="goodsList" border size="small" max-height="300">
            <el-table-column prop="name" label="商品名称" min-width="120">
              <template slot-scope="scope">
                <div class="goods-name-cell">
                  <div v-if="scope.row.imageUrl" class="goods-image-container">
                    <el-image
                      :src="scope.row.imageUrl"
                      :preview-src-list="scope.row.imageList || []"
                      class="goods-image"
                      fit="contain"
                    >
                      <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </el-image>
                    <div v-if="scope.row.imageList && scope.row.imageList.length > 1" class="image-count">
                      <i class="el-icon-picture"></i> {{scope.row.imageList.length}}
                    </div>
                  </div>
                  <span class="goods-name">{{ scope.row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="商品类型" width="100"></el-table-column>
            <el-table-column prop="brand" label="品牌" width="100"></el-table-column>
            <el-table-column prop="unit" label="单位" width="80" align="center"></el-table-column>
            <el-table-column prop="quantity" label="库存" width="100" align="right">
              <template slot-scope="scope">
                {{ scope.row.quantity }} {{ scope.row.unit }}
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" width="100" align="right">
              <template slot-scope="scope">
                {{ scope.row.price }} 元
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="100">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.remark && scope.row.remark !== '-'" :content="scope.row.remark"
                            placement="top">
                  <span class="remark-text">{{ scope.row.remark }}</span>
                </el-tooltip>
                <span v-else>{{ scope.row.remark }}</span>
              </template>
            </el-table-column>
          </el-table>
          <div v-else class="no-goods-data">暂无商品数据</div>

          <!-- 添加额外的商品图片展示区域 -->
          <div v-if="goodsList.length > 0 && goodsList[0].introduceImages && goodsList[0].introduceImages.length > 0" class="additional-images">
            <h4>商品介绍图</h4>
            <div class="image-list">
              <div v-for="(img, idx) in goodsList[0].introduceImages" :key="'intro-'+idx" class="image-item">
                <el-image
                  :src="img"
                  :preview-src-list="goodsList[0].introduceImages"
                  fit="cover"
                  class="preview-image"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
            </div>
          </div>

          <div v-if="goodsList.length > 0 && goodsList[0].paramImages && goodsList[0].paramImages.length > 0" class="additional-images">
            <h4>参数图</h4>
            <div class="image-list">
              <div v-for="(img, idx) in goodsList[0].paramImages" :key="'param-'+idx" class="image-item">
                <el-image
                  :src="img"
                  :preview-src-list="goodsList[0].paramImages"
                  fit="cover"
                  class="preview-image"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
            </div>
          </div>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script>
import SignaturePad from './SignaturePad.vue';
import {getOrderDetail, getPsorders} from "@/api/supply/psorders";
import {signatureFileUpload} from "@/api/common/file";
import {getToken, setToken} from "@/utils/auth";
import {updateFlowTemplateSign, updateSign} from "@/api/supply/flowTemplate";
import axios from "axios";

export default {
  name: 'SignatureView',
  components: {
    SignaturePad
  },
  data() {
    return {
      loading: true,
      error: '',
      approvalId: '',
      nodeId: '',
      token: '',
      approvalNodeName: '',
      approvalUserName: '',
      approvalRoles: '',
      showAmount: false,
      approvalAmount: 0,
      showGoodsInfo: false,
      goodsList: [],
      orderId: '',
      nodeName: '',
      orderDetail: null,
      signatureImage: '',
      signatureCompleted: false,
      uploadedImageUrl: ''
    };
  },
  created() {
    this.orderId = this.$route.query.orderId;
    this.nodeId = this.$route.query.nodeId;
    this.nodeName = this.$route.query.nodeName;
    this.token = this.$route.query.token;
    setToken(this.token)
    this.approvalRoles = this.$route.query.approvalRoles || '';
    this.approvalUsers = this.$route.query.approvalUsers || '';

    if (!this.orderId || !this.nodeId) {
      this.error = '缺少必要的审批信息';
      this.loading = false;
      return;
    }
    this.approvalId = this.orderId;
    this.approvalNodeName = this.nodeName || '审批节点';
    this.approvalUserName = this.approvalUsers;

    // 获取订单详情
    this.fetchApprovalData();
  },
  methods: {
    // 获取审批数据
    fetchApprovalData() {
      this.loading = true;

      // 从后端获取订单详情
      getPsorders(this.orderId).then(response => {
        if (response && response.data) {
          // 设置订单详情
          const orderData = response.data;
          this.showAmount = true;
          this.approvalAmount = orderData.orderAmount || '0.00';

          // 获取商品详情
          this.getProductInfoByOrderId(this.orderId);
        } else {
          this.error = '获取订单信息失败';
          this.loading = false;
        }
      }).catch(err => {
        console.error('获取订单详情失败:', err);
        this.error = '获取订单信息失败';
        this.loading = false;
      });
    },

    // 处理签名完成
    handleSignatureComplete(signatureData) {
      console.log('签名完成：', signatureData);
      this.signatureImage = signatureData.signatureData;

      // 将base64转换为Blob对象
      this.uploadSignatureImage(this.signatureImage);
    },

    // 上传签名图片（直接使用axios）
    async uploadSignatureImage(base64Image) {
      try {
        // 添加Base64格式验证
        if (!base64Image.startsWith('data:image/')) {
          throw new Error('无效的签名图像格式');
        }
        // 采用更可靠的Blob转换方法
        const res = await fetch(base64Image);
        const blob = await res.blob();
        console.log('生成Blob:', blob.size + ' bytes', blob.type);
        // 创建FormData
        const formData = new FormData();
        const filename = `signature_${Date.now()}.png`;
        formData.append('file', blob, filename);

        // 调试FormData内容
        Array.from(formData.entries()).forEach(([key, val]) => {
          console.log(`FormData字段: ${key}`, val);
        });

        // 直接使用axios上传
        try {
          const response = await axios({
            method: 'post',
            url: process.env.VUE_APP_BASE_API + '/file/upload',  // 使用环境变量中的API地址
            data: formData,
            headers: {
              'Content-Type': 'multipart/form-data',
              'Authorization': 'Bearer ' + getToken()
            }
          });

          console.log('上传响应:', response);

          if (response.data.code === 200) {
            console.log('文件地址:', response.data.data.url);
            this.uploadedImageUrl = response.data.data.url;
            this.signatureCompleted = true;

            // 更新签名信息
            const updateRes = await updateSign(this.orderId, response.data.data.url);
            if (updateRes.code === 200) {
              this.$message.success('签名上传成功');
              // 延迟后返回
              setTimeout(() => {
                this.goBack();
              }, 1500);
            } else {
              this.$message.error(updateRes.msg || '签名信息更新失败');
            }
          } else {
            throw new Error(response.data.msg || '上传失败');
          }
        } catch (error) {
          console.error('上传错误:', error);
          this.$message.error('上传失败，请检查网络连接');
        }
      } catch (error) {
        console.error('上传过程异常:', error);
        this.$message.error('签名上传失败: ' + error.message);
      }
    },

    // 获取商品详情
    getProductInfoByOrderId(orderId) {
      this.loading = true;
      getOrderDetail(orderId).then(response => {
        if (response.code === 200 && response.data) {
          console.log("订单详情数据:", response.data);

          // 确保处理列表形式的数据
          let dataList = Array.isArray(response.data) ? response.data : [response.data];

          // 清空现有商品列表
          this.goodsList = [];

          // 如果有数据，设置显示商品信息标志
          if (dataList.length > 0) {
            this.showGoodsInfo = true;

            // 遍历所有商品数据
            dataList.forEach(item => {
              // 检查是否是新的数据格式
              if (item.prodInfo) {
                // 处理新格式数据
                const prodInfo = item.prodInfo;
                const prodInfoPro = item.prodInfoPro || {};

                // 处理图片URL
                let imageList = [];
                if (prodInfo.imageUrl) {
                  imageList = prodInfo.imageUrl.split(',').filter(url => url.trim() !== '');
                }

                // 处理额外的商品图片
                let introduceImages = [];
                if (prodInfoPro.prodIntroduceImgUrls) {
                  introduceImages = prodInfoPro.prodIntroduceImgUrls.split(',').filter(url => url.trim() !== '');
                }

                let paramImages = [];
                if (prodInfoPro.prodParamImgUrls) {
                  paramImages = prodInfoPro.prodParamImgUrls.split(',').filter(url => url.trim() !== '');
                }

                let detailImages = [];
                if (prodInfoPro.prodDetailImgUrls) {
                  detailImages = prodInfoPro.prodDetailImgUrls.split(',').filter(url => url.trim() !== '');
                }

                let applyImages = [];
                if (prodInfoPro.prodApplyImgUrls) {
                  applyImages = prodInfoPro.prodApplyImgUrls.split(',').filter(url => url.trim() !== '');
                }

                // 合并所有商品图片列表以便预览
                const allImages = [...imageList, ...introduceImages, ...paramImages, ...detailImages, ...applyImages];

                // 添加到商品列表
                this.goodsList.push({
                  id: prodInfo.id,
                  name: prodInfo.name || '暂无名称',
                  imageUrl: imageList.length > 0 ? imageList[0] : '', // 第一张图作为主图
                  imageList: allImages, // 所有图片列表用于预览
                  type: prodInfo.type || '-',
                  brand: prodInfo.brand || '-',
                  spec: `${prodInfo.nature || ''} ${prodInfo.brand || ''}`.trim() || '-',
                  quantity: prodInfo.stockQuantity || 0,
                  unit: prodInfo.minUnit || '个',
                  price: prodInfo.unitPrice || 0,
                  status: prodInfo.status,
                  remark: prodInfo.remark || '-',
                  // 添加额外图片信息用于可能的扩展展示
                  introduceImages: introduceImages,
                  paramImages: paramImages,
                  detailImages: detailImages,
                  applyImages: applyImages
                });
              } else {
                // 处理旧格式数据
                let imageList = [];
                if (item.imageUrl) {
                  imageList = item.imageUrl.split(',').filter(url => url.trim() !== '');
                }

                this.goodsList.push({
                  id: item.id,
                  name: item.name || '暂无名称',
                  imageUrl: imageList.length > 0 ? imageList[0] : '',
                  imageList: imageList,
                  type: item.type || '-',
                  brand: item.brand || '-',
                  spec: `${item.nature || ''} ${item.brand || ''}`.trim() || '-',
                  quantity: item.stockQuantity || 0,
                  unit: item.minUnit || '个',
                  price: item.unitPrice || 0,
                  status: item.status,
                  remark: item.remark || '-'
                });
              }
            });

            console.log("处理后的商品列表:", this.goodsList);
          } else {
            this.showGoodsInfo = false;
          }

          this.loading = false;
        } else {
          this.$message.error(response.msg || '获取商品详情失败');
          this.loading = false;
        }
      }).catch(error => {
        console.error('获取商品详情失败:', error);
        this.$message.error('获取商品详情失败');
        this.loading = false;
      });
    },

    goBack() {
      this.$router.push({name: 'LeaderApproval'});
    }
  }
};
</script>

<style lang="scss" scoped>
.signature-view {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 100px);
  padding: 20px;
  background-color: #f0f2f5;
}

.signature-card {
  width: 100%;
  max-width: 800px;

  .el-card__body {
    padding: 0 !important;
  }
}

.goods-info {
  padding: 15px;
  background-color: #fff;

  h3 {
    margin-bottom: 15px;
    font-size: 16px;
    font-weight: bold;
    color: #303133;
  }

  .no-goods-data {
    text-align: center;
    color: #909399;
    padding: 20px 0;
  }
}

.goods-name-cell {
  display: flex;
  align-items: center;

  .goods-image-container {
    position: relative;
    width: 50px;
    height: 50px;
    margin-right: 10px;
    border: 1px solid #eee;
    border-radius: 4px;
    overflow: hidden;
  }

  .image-count {
    position: absolute;
    bottom: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    font-size: 12px;
    padding: 2px 4px;
    border-top-left-radius: 4px;
  }

  .goods-image {
    width: 100%;
    height: 100%;
    display: block;
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 20px;
  }

  .goods-name {
    flex: 1;
    word-break: break-all;
  }
}

.remark-text {
  display: inline-block;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  color: #909399;

  i {
    font-size: 40px;
    margin-bottom: 15px;
  }

  p {
    font-size: 16px;
    margin-bottom: 20px;
  }
}

.additional-images {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #ebeef5;
}

.additional-images h4 {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #606266;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.image-item {
  width: 100px;
  height: 100px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  display: block;
}

@media (max-width: 768px) {
  .signature-view {
    padding: 10px;
    min-height: calc(100vh - 60px);
  }
}
</style>
